/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vote;

//import java.beans.Statement;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author theInterloper
 */
@WebServlet(name = "voteManager", urlPatterns = {"/voteManager"})
public class voteManager extends HttpServlet {

    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
     
    int bush = 0;
    int kerry = 0;
    String emailAddress;
    String password;

    int voteCast = 0;
    
        
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        System.out.println("Process Request is triggered");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        boolean registered = false;
        boolean loggedIn = false;
        boolean voted = false;
        
        System.out.println("votes for Bush: "+bush 
                + "\nvotes for Kerry " + kerry 
                +"\nemail address " + emailAddress 
                + "\npassword " + password);

        registered = Boolean.parseBoolean(request.getParameter("registerSubmit"));
        pageForward(registered, loggedIn, voted, out); 
        
        emailAddress = request.getParameter("emailReturn");
        System.out.println("The email address entered is " + emailAddress);
        password = request.getParameter("passwordReturn");
        System.out.println("The password entered is " + password);
        
        loggedIn = Boolean.parseBoolean(request.getParameter("loginSubmit"));
        pageForward(registered, loggedIn, voted, out); 
        
        if (loggedIn == true && voteCast == 1){
                     
            System.out.println("The user is logged in\n");
            voteCast = Integer.parseInt(request.getParameter("voteReturn"));
            voted = Boolean.parseBoolean(request.getParameter("voteSubmit"));
        
        }
        
        if (voteCast == 1){
            bush = 1;
        }
        if (voteCast == 2){
            kerry = 1;
        }
        
        
        String putAll = "INSERT INTO db1075072_voter.votes (bush, kerry, emailAddress, password) VALUES (" + bush +","+ kerry + ",'"+ emailAddress + "', '" + password + "')"; 
        Statement statement = setUpConnection().createStatement();
         
        if (voted == true){
              statement.executeUpdate(putAll);
              System.out.println("The following has been commited to the DB:\n" 
                      + "votes for bush: " + bush 
                      + "\nvotes for kerry: " + kerry 
                      + "\nentered email address: " + emailAddress 
                      + "\nentered password: " + password);
            }
      
        try {
     
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Did it work?</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet voteManager at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
            
            if (voteCast == 1){
                out.println("<p>You voted for George Bush </p>");      
            }
            
            if (voteCast == 2){
                out.println("<p>You voted for John Kerry </p>");    
            }
            out.println(getTotals());
           
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(voteManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(voteManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private Connection setUpConnection() throws SQLException {
     String driver= ("com.mysql.jdbc.Driver");
     String url = "jdbc:mysql://mysql1115.cp.blacknight.com/db1075072_voter";
     Connection connection = DriverManager.getConnection(url,"u1075072_Voter", "testvoter");
     try {
            // Load database driver if not already loaded.
            Class.forName(driver);
           } catch(ClassNotFoundException cnfe) {
                System.err.println("Error loading driver: " + cnfe);
           } 
     return connection;
    }

    private void pageForward(boolean registered, boolean loggedIn, boolean voted, PrintWriter out) {
        
        Character cma = '"';
//        String registerURL = "<meta http-equiv=" + cma + "REFRESH" + cma + "content=" + cma + "0;url=http://ec2-46-137-27-146.eu-west-1.compute.amazonaws.com:8080/webVoterFinal/RegisterForm/register.html" + cma + ">";
//        String loginURL = "<meta http-equiv=" + cma + "REFRESH" + cma + "content=" + cma + "0;url=http://ec2-46-137-27-146.eu-west-1.compute.amazonaws.com:8080/webVoterFinal/LoginForm/login.html" + cma + ">";
//        String voteURL = "<meta http-equiv=" + cma + "REFRESH" + cma + "content=" + cma + "0;url=http://ec2-46-137-27-146.eu-west-1.compute.amazonaws.com:8080/webVoterFinal/VotingForm/vote.html" + cma + ">";
        
        String registerURL = "<meta http-equiv=" + cma + "REFRESH" + cma + "content=" + cma + "0;url=http://localhost:8080/webVoterFinal/RegisterForm/register.html" + cma + ">";
        String loginURL = "<meta http-equiv=" + cma + "REFRESH" + cma + "content=" + cma + "0;url=http://localhost:8080/webVoterFinal/LoginForm/login.html" + cma + ">";
        String voteURL = "<meta http-equiv=" + cma + "REFRESH" + cma + "content=" + cma + "0;url=http://localhost:8080/webVoterFinal/VotingForm/vote.html" + cma + ">";
        
        
        if (registered == true){
                out.println(loginURL);
            }
            if (loggedIn == true){
                out.println(voteURL);
            }
           
    }

    private String getTotals() throws SQLException {
        
        Statement statement = setUpConnection().createStatement();
        String getBushVotes = "SELECT SUM(bush)FROM votes";
        String getKerryVotes = "SELECT SUM(kerry)FROM votes";
        String kerryTotal = "";
        String bushTotal = "";
        String output = "";
        
         ResultSet resultSetK = statement.executeQuery(getKerryVotes);
        // Print results.
        while(resultSetK.next()) {
            kerryTotal += (resultSetK.getString(1));  
        }
        ResultSet resultSetB = statement.executeQuery(getBushVotes);
        // Print results.
        while(resultSetB.next()) {
            bushTotal += (resultSetB.getString(1));  
        }
        output +=("<p>George Bush has a total of "+ bushTotal +" votes</p>");
        output +=("<p>John Kerry has a total of "+ kerryTotal +" votes</p>");
        
        return output;
    }

   

    
}
